﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using WorkStation.Frameworks.Core;
using WorkStation.Frameworks.Core.Extensions;
using WorkStation.Frameworks.EasyBus;
using WorkStation.Frameworks.EasyBus.DbModel;
using WorkStation.Frameworks.EasyBus.Pipeline;
using WorkStation.Frameworks.EasyBus.Pipeline.Filters;
using WorkStation.Frameworks.EasyBus.Pipeline.Handles;

namespace WorkStation.Frameworks.EasyBus.Handles
{
    /// <summary>
    /// 订阅端处理路由处理器
    /// </summary>
    public class ProcessRouteHandle : Handle
    {
        public static readonly string NAME = "EasyBus.ProcessRouteHandle";

        public IMessageListener Listener { get; set; }

        public ProcessRouteHandle() 
        {
            this.Name = ProcessRouteHandle.NAME;
            this.Order = -100;
            this.Filter = new LambdaFilter() { Expression = v => (v as Message).IsRecordingHistory };
        }

        protected override HandleResult InnerExecute(ActionContext context)
        {
            // 在历史记录中找出已经处理成功的 Handle 名称，把它们加入忽略列表

            Message msg = context.Input as Message;

            try
            {
                IBus bus = (context as BusActionContext).Bus;

                IBusDataManager manager = bus as IBusDataManager;

                IEnumerable<MessageProcessLog> logs = manager.HistoryCenterRepository.GetMessageProcessLogById(msg.MessageId);

                (context.Args[ActionContext.IGNORE_HANDLE_KEY] as List<string>).AddRange(logs.Where(v => v.IsSuccess = true && v.BusName.Equals(bus.Name) && v.ListenerName.Equals(this.Listener.Name)).Select(v => v.HandleName));
            }
            catch (Exception ce)
            {
                context.IsContinue = false;

                return new ProcessRouteHandleErrorResult(context.Input, this, ce.ToString(), ce);
            }

            return new SuccessHandleResult(context.Input, this, "{0} process success.".Fmt(typeof(ProcessRouteHandle).FullName));
        }
    }

    public class ProcessRouteHandleErrorResult : FailHandleResult
    {
        public ProcessRouteHandleErrorResult(object input, IHandle handle, string errorMessage = null, Exception exception = null) : base(input, handle, errorMessage, exception)
        {
        
        }
    }
}
